package com.biostime.qdingding.modules.qd.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.persistence.Page;
import com.biostime.qdingding.common.utils.DateUtils;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.api.dto.BalanceDto;
import com.biostime.qdingding.modules.qd.entity.Attach;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.Privilege;
import com.biostime.qdingding.modules.qd.entity.Promotionset;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.entity.Studentproms;
import com.biostime.qdingding.modules.qd.entity.Transrecord;
import com.biostime.qdingding.modules.qd.service.AttachService;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.MemberService;
import com.biostime.qdingding.modules.qd.service.MembercenterService;
import com.biostime.qdingding.modules.qd.service.MemberstudentService;
import com.biostime.qdingding.modules.qd.service.PrivilegeService;
import com.biostime.qdingding.modules.qd.service.PromotionsetService;
import com.biostime.qdingding.modules.qd.service.StudentService;
import com.biostime.qdingding.modules.qd.service.StudentpromsService;
import com.biostime.qdingding.modules.qd.service.TransrecordService;
import com.biostime.qdingding.modules.sys.entity.User;
import com.biostime.qdingding.modules.sys.service.UserService;
import com.biostime.qdingding.modules.sys.utils.UserUtils;

/**
 * 合同Controller
 * @author king
 * @version 2015-11-05
 */
@Controller
@RequestMapping(value = "${adminPath}/qd/contract")
public class ContractController extends BaseController {

	@Autowired
	private ContractService contractService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private StudentService studentService ;
	@Autowired
	private MembercenterService memberCenterService;
	@Autowired
	private TransrecordService transrecordService;	
	@Autowired
	private MemberstudentService memberstudentService;
	@Autowired
	private UserService userService;
	@Autowired
	private PromotionsetService promotionsetService;
    @Autowired
    private StudentpromsService studentpromsService;
    @Autowired 
    private PrivilegeService privilegeService;
    @Autowired
    private AttachService attachService;

	@ModelAttribute
	public Contract get(@RequestParam(required=false) String id) {
		Contract entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = contractService.get(id);
		}
		if (entity == null){
			entity = new Contract();
		}
		return entity;
	}
	
	@RequestMapping(value={"ajax"})
	public void getId(HttpServletRequest request,HttpServletResponse response){
		//获取js返回的method参数进行一个判定
		String method = request.getParameter("method");
		
		if(method!=null && method.equalsIgnoreCase("getmemberid") ){//获取会员信息
			try {
				String memberMobile = request.getParameter("memberMobile");
				String memberName = request.getParameter("memberName");
				if(StringUtils.isEmpty(memberMobile) && StringUtils.isEmpty(memberName)){
					response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", "","系统未发现注册该手机号的会员"));
					return;
				};
				
				Member member = new Member();
			    member.setMobile(memberMobile);
			    //member.setName(memberName);
			    List<Member> memList = null; 
			    if(!StringUtils.isEmpty(memberMobile)){
			    	memList = memberService.findListByMobile(member); 
			    }
			    
			    //该手机号已绑定过会员 则无法再绑定其他会员
				if(memList !=null && memList.size() > 0){
					if(memList.size()==1){
						for(Member mem : memList){
			    			response.getWriter().write(String.format("<option selected=\"selected\" value=\"%s\">%s</option>\n", mem.getId(),mem.getNikename()));
			    		}
					}else{
						response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","系统发现多个匹配会员，请选择..."));
						for(Member mem : memList){
			    			response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", mem.getId(),mem.getNikename()));
			    		}
					}
			    }else{
			    	response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", "","系统未发现注册该手机号的会员"));
			    }
			} catch (IOException e) {
				e.printStackTrace();
				logger.error(String.format("获取会员信息异常：%s:%s", e.getMessage(),e.getStackTrace()));
			}
		}else if(method!=null && method.equalsIgnoreCase("getstudentid")){//获取学员信息
			
			try{
				String studentName = request.getParameter("studentName");
				if( StringUtils.isEmpty(studentName)){
					response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", "","输入学员姓名,系统自动查询"));
					return;
				};
				
				Student student = new Student();
				student.setName(studentName);
				List<Student> stuList = studentService.findListByName(student); 
				if(stuList!=null && stuList.size() > 0){
					//查找是否存在有手机号绑定学员
					if(stuList.size()==1){
						for(Student stu : stuList){
							String sexStr = "";
							if(stu.getSex() == 0){
								sexStr = "男";
							}else if(stu.getSex() == 1){
								sexStr = "女";
							}else if(stu.getSex() == -1){
								sexStr = "未知";
							}
							response.getWriter().write(String.format("<option selected=\"selected\" value=\"%s\">%s</option>\n", stu.getId(),stu.getName()+"&nbsp;"+DateUtils.formatDate(stu.getBirthday(), "yyyy-MM-dd")+"&nbsp;"+sexStr+"&nbsp;"+stu.getMobile()));
							response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","新建学员"));
						}
					}else{
						response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","系统发现多个匹配学员，请选择..."));
						for(Student stu : stuList){
							String sexStr = "";
							if(stu.getSex() == 0){
								sexStr = "男";
							}else if(stu.getSex() == 1){
								sexStr = "女";
							}else if(stu.getSex() == -1){
								sexStr = "未知";
							}
							response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", stu.getId(),stu.getName()+"&nbsp;"+DateUtils.formatDate(stu.getBirthday(), "yyyy-MM-dd")+"&nbsp;"+sexStr+"&nbsp;"+stu.getMobile()));
						}
							response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n","","新建学员"));
					}
				}else{
					response.getWriter().write(String.format("<option value=\"%s\">%s</option>\n", "","系统未发现该姓名的学员"));
				}
			}catch (IOException e) {
				e.printStackTrace();
				logger.error(String.format("获取学员信息异常：%s:%s", e.getMessage(),e.getStackTrace()));
			}
		}
	}
	
	@RequestMapping("getbroken")
	public void getBroken(HttpServletRequest request, HttpServletResponse response){
		String method = request.getParameter("method");
		if(method != null &&method.equalsIgnoreCase("getbrokenbyid") ){
			String contractid = request.getParameter("contractid");
			if(!StringUtils.isEmpty(contractid)){
				Contract contract = contractService.get(contractid);
				try {
					if(contract != null)
					response.getWriter().write(contract.getBroken()+"");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return;
		}
		String isFree = request.getParameter("isFree");
		if(isFree.equals("1")){
			try {
				response.getWriter().write("0");
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		String code = request.getParameter("code");
		String contractId = request.getParameter("contractid");
		Contract contract = new Contract();
		contract.setCenter(UserUtils.getUser().getCenter());
		String nowCode = contractService.getLateCode(contract);
		try {
			if(code != null && code != ""){
				if(nowCode == null){
					response.getWriter().write("0");
					return;
				}
				int num = StringUtils.toInteger(code);
				int nowNum = StringUtils.toInteger(nowCode);
				
			 if((num-1) == nowNum){
					response.getWriter().write("0");
					return;
				}else if(num > nowNum ){
					response.getWriter().write("1");
					return;
				}else if(num <= nowNum ){
					if(contractId != null && contractId != ""){
						return;
					}else{
						response.getWriter().write("2");
						return;
					}
				}
			}
		} catch (IOException e) {
			try {
				response.getWriter().write("-1");
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping("getlimitdate")
	public void getLimitDate(HttpServletRequest request,HttpServletResponse response){
		String validityTime = request.getParameter("validityTime");
		String signDatestr = request.getParameter("signDate");
		if(signDatestr != null && signDatestr !=""){
			Date signDate = DateUtils.parseDate(signDatestr);
			int signYear = signDate.getYear();
			int signMonth = signDate.getMonth();
			int month = signMonth+Integer.valueOf(validityTime);
			while(month > 12){
				signYear++;
				month-=12;
			}
			signDate.setYear(signYear);
			signDate.setMonth(month);
			try {
				response.getWriter().write(DateUtils.formatDate(signDate, "yyyy-MM-dd"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@RequiresPermissions(value={"qd:addtran:add"})
	@RequestMapping("addtransrecord")
	public String dialog(Contract contract,HttpServletRequest request,HttpServletResponse response,Model model){
		
//		String contractId = request.getParameter("contractId");
//		String memberId = request.getParameter("memberId");
//		String studentId = request.getParameter("studentId");
		
		Transrecord transrecord = new Transrecord();
		transrecord.setInout(0);
		transrecord.setPayDate(new Date());
		transrecord.setInvalid(0);
		transrecord.setCourseorderId(0);
		transrecord.setType("0");
		transrecord.setPayType("0");
//		transrecord.setContractId(Integer.valueOf(contractId));
//		transrecord.setStudentId(Integer.valueOf(studentId));
//		transrecord.setMemberId(Integer.valueOf(memberId));
		
		model.addAttribute("contract", contract);
		model.addAttribute("transrecord", transrecord);
		return "modules/qd/transrecordDialog";
	}
	
	@RequiresPermissions("qd:contract:view")
	@RequestMapping(value = {"detail"})
	public String detail(Contract contract ,HttpServletRequest request, HttpServletResponse response, Model model) {
		
		//优惠信息
		List<String> proms = promotionsetService.getProms(contract);
		
		//合同余额
		if(contract.getAbort() != null  && contract.getAbort() != 1){
			double balance = contractService.getBalance(contract);
			model.addAttribute("balance", balance);
			
			BalanceDto dto = transrecordService.getBalance(contract.getStudent());
			model.addAttribute("frozenBalance", dto.getSumFreeze());
		}
		//特权
		List<Privilege> privileges = null;
		Privilege demo = new Privilege(); 
		demo.setContractId(StringUtils.toInteger(contract.getId()));
		privileges = privilegeService.findList(demo);
		
		if( privileges != null  ){
			for(Privilege priv : privileges){
				if(priv.getType().equals("leave")){
					contract.setLeavePriv(priv);
				}
				if(priv.getType().equals("abort")){
					contract.setAbortPriv(priv);
				}
			}
		}
		
		Page<Transrecord> page = null;
		if(contract != null && !StringUtils.isEmpty(contract.getId())){
			Transrecord transrecord = new Transrecord();
			if(contract.getId() != null){
				transrecord.setContractId(Integer.valueOf(contract.getId()));
			}
			page = transrecordService.findPage(new Page<Transrecord>(request, response), transrecord); 
		}
		
		//附件
		List<Attach> contractAttach = new ArrayList<Attach>();
		Attach attach = new Attach();
		attach.setCategory("contract");
		attach.setObjectId(StringUtils.toInteger(contract.getId()));
		contractAttach = attachService.findList(attach);
		
		model.addAttribute("proms", proms);
		model.addAttribute("page", page);
		model.addAttribute("contractAttach", contractAttach);
		model.addAttribute("contract", contract);
		return "modules/qd/contractDetail";
	}
	
	@RequiresPermissions("qd:contract:view")
	@RequestMapping(value = {"list",""})
	public String list(Contract contract ,HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Contract> page = contractService.findPage(new Page<Contract>(request, response), contract); 
		model.addAttribute("page", page);
		return "modules/qd/contractList";
	}

	@RequestMapping(value = {"getprom"})
	public void getProm(@RequestParam String setId ,HttpServletRequest request, HttpServletResponse response) {
		try {
			response.getWriter().write(promotionsetService.getPromHint(setId));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@SuppressWarnings("deprecation")
	@RequiresPermissions("qd:contract:view")
	@RequestMapping(value = "form")
	public String form(Contract contract,HttpServletRequest request,HttpServletResponse response,Model model) {
		
		contract.setCenter(UserUtils.getUser().getCenter());
		
		User user = new User();
		
		if( contract.getSales() != null)
			user.setName(contract.getSales().getName());
		
		List<User> userList = userService.findList(user);
		
		Page<Transrecord> page = null;
		if(contract != null && !StringUtils.isEmpty(contract.getId())){
			Transrecord transrecord = new Transrecord();
			if(contract.getId() != null){
				transrecord.setContractId(Integer.valueOf(contract.getId()));
			}
			page = transrecordService.findPage(new Page<Transrecord>(request, response), transrecord); 
		}
		 
		//会员列表
		List<Member> memberList = null;
		//学员列表
		List<Student> studentList = null;
		//优惠列表
		List<Promotionset> promotionsetList = null;
		Promotionset promotionset = new Promotionset();
		promotionsetList = promotionsetService.findList(promotionset);
		//特权
		List<Privilege> privileges = null;
		if(!contract.getIsNewRecord()){
			Privilege demo = new Privilege(); 
			demo.setContractId(StringUtils.toInteger(contract.getId()));
			privileges = privilegeService.findList(demo);
			
			if( privileges != null  ){
				for(Privilege priv : privileges){
					if(priv.getType().equals("leave")){
						contract.setLeavePriv(priv);
					}
					if(priv.getType().equals("abort")){
						contract.setAbortPriv(priv);
					}
				}
			}
			
			Member member = contract.getMember();
			memberList = memberService.findList(member);
			
			Student student = 	contract.getStudent();
			studentList = studentService.findList(student);
			
			Studentproms studentproms = new Studentproms();
			studentproms.setStudentId(Integer.valueOf(contract.getStudent().getId()));
			Map<String, String> proms = studentpromsService.findMapsByStudentId(studentproms);
			
			for(Promotionset temp : promotionsetList ){
				if (proms.containsKey(temp.getId())) {
					temp.setChecked(true);
				}
			}
		}
		if(!StringUtils.isEmpty(contract.getId()))
			contract.setValidityTime(((contract.getLimitDate().getYear()-contract.getSignDate().getYear())*12)+(contract.getLimitDate().getMonth()-contract.getSignDate().getMonth()));
		
		if(!StringUtils.isEmpty(contract.getId())){
			List<Attach> contractAttach = new ArrayList<Attach>();
			Attach attach = new Attach();
			attach.setCategory("contract");
			attach.setObjectId(StringUtils.toInteger(contract.getId()));
			contractAttach = attachService.findList(attach);
			model.addAttribute("contractAttach", contractAttach);
		}
		
		model.addAttribute("userList", userList);
		model.addAttribute("page", page);
		model.addAttribute("studentList",studentList);
		model.addAttribute("memberList",memberList);
		model.addAttribute("promotionsetList", promotionsetList);
		model.addAttribute("contract", contract);
		return "modules/qd/contractForm";
	}

	@RequiresPermissions(value={"qd:contract:edit","qd:contract:add"}, logical=Logical.OR)
	@RequestMapping(value = "save")
	public synchronized String save(Contract contract, Model model, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, contract)){
			return form(contract,request,response, model);
		}
		
		/**判断合同过期日期在当前时间之后**/
		if(!contract.getLimitDate().after(contract.getSignDate())){
			model.addAttribute("message", "合同到期日期必须在合同签订日期之后");
			return form(contract,request,response, model);
		}
		
		if(StringUtils.isEmpty(contract.getId()) && !StringUtils.isEmpty(contract.getStudent().getId())){
			Contract studentContract = contractService.getByStudentId(Integer.parseInt(contract.getStudent().getId()));
			if(studentContract != null){
				if("free".equalsIgnoreCase(studentContract.getType())){
					studentContract.setAbort(1);
					studentContract.setStatus(1);
					contractService.freeSave(studentContract);
				}else{
					model.addAttribute("message", "该宝宝已有一份正常生效合同 如需新增请中止该合同");
					return form(contract,request,response, model);
				}
			}
		}
		Contract existContract = contractService.getByMobileStatus(contract);
		
		if(existContract!=null && StringUtils.isEmpty(contract.getId())){
			//给查出来的这个合同set特权信息
			Date limitDate = existContract.getLimitDate(); 
			
			//判定合同是否过期
			if(limitDate.after(new Date())){
				if(existContract.getAbort() == 0 ){
					if("free".equalsIgnoreCase(existContract.getType())){
						existContract.setAbort(1);
						contractService.freeSave(existContract);
					}else{
						model.addAttribute("message", "该手机号已经存在生效的合同");
						return form(contract,request,response, model);
					}
				}
			}
		}
		 
		try{
			contractService.save(contract,request);
		}catch(Exception e){
			e.printStackTrace();
			model.addAttribute("message", "创建合同失败");
			return form(contract,request,response, model);
		}
		
		addMessage(redirectAttributes, "保存成功");
		Contract cont = contractService.findList(contract).get(0);
		//保存附件
		String[] attachs = request.getParameterValues("hid_attach_name");
		String[] remarks = request.getParameterValues("hid_attach_remark");
		if(cont != null && !StringUtils.isEmpty(cont.getId())	){
			Attach att = new Attach();
			att.setCategory("contract");
			att.setObjectId(StringUtils.toInteger(cont.getId()));
			attachService.deleteAll(att);
			if(attachs != null){
				for(int i = 0;i<attachs.length;i++){
					String name = attachs[i];
					String remark = remarks[i];
					if(!StringUtils.isEmpty(name)){
						String[] parts = name.split("\\|");
						Attach attach = new Attach();
						attach.setObjectId(StringUtils.toInteger(cont.getId()));
						attach.setCategory(parts[0]);
						attach.setFileName(parts[1]);
						attach.setFilePath(parts[2]);
						attach.setFileSize(StringUtils.toInteger(parts[3]));
						attach.setRemarks(remark);
						attachService.save(attach);
					}
				}
			}
			
		}	
		return "redirect:"+Global.getAdminPath()+"/qd/contract/?repage";
	}
	
	/**
	 * 合同中止
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("qd:contract:abort")
	@RequestMapping(value="abort")
	public String abort(HttpServletRequest request,RedirectAttributes redirectAttributes){
		String id = request.getParameter("id");
		Contract contract = contractService.get(id);
		if(contract != null){
			contract.setAbort(1);
			contractService.save(contract);
		}
		addMessage(redirectAttributes, "中止成功");
		return "redirect:"+Global.getAdminPath()+"/qd/contract/?repage";
	}
	
	@RequiresPermissions("qd:contract:delete")
	@RequestMapping(value = "delete")
	public String delete(@RequestParam(value="ids",required=false) String idsRequest, Contract contract, RedirectAttributes redirectAttributes) {
		//批量删除
		if(!StringUtils.isEmpty(idsRequest)){
			String[] ids = idsRequest.split(",");
			for(String id : ids){
				contractService.delete(new Contract(id));
			}
		}else{
			contractService.delete(contract);
		}
		addMessage(redirectAttributes, "删除成功");
		return "redirect:"+Global.getAdminPath()+"/qd/contract/?repage";
	}

}
